package com.example.common.utils;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.widget.EditText;

import com.example.common.R;

import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author skygge
 * @date 2020-01-08.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：限制EditText输入的字符类型，如换行，空格，特殊字符，表情等
 */
public class InputFilterUtil {

    public static void setEditTextInhibitInputSpaChat(Context context, EditText editText) {

        //常见特殊字符
        InputFilter filter_speChat = (charSequence, i, i1, spanned, i2, i3) -> {
            String speChat = "[`~!@#_$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）+|{}【】‘；：”“’。，、？]";
            Pattern pattern = Pattern.compile(speChat);
            Matcher matcher = pattern.matcher(charSequence.toString());
            if (matcher.find()) {
                CustomToastUtil.showToast(context, context.getString(R.string.name_contains_illegal_characters));
                return "";
            }
            else return null;
        };

        //表情过滤器
        InputFilter emojiFilter = (source, start, end, dest, dstart, dend) -> {
            Pattern emoji = Pattern.compile(
                    "[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                    Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
            Matcher emojiMatcher = emoji.matcher(source);
            if (emojiMatcher.find()) {
                CustomToastUtil.showToast(context, context.getString(R.string.name_contain_emoji));
                return "";
            }
            return null;
        };
        editText.setSingleLine(true);
        editText.setFilters(new InputFilter[]{filter_speChat, emojiFilter});
        editText.addTextChangedListener(new TextWatcher() {
            private CharSequence sequence;
            private int start;
            private int end;
            @Override
            public void beforeTextChanged(CharSequence s, int i, int i1, int i2) {
                sequence = s;
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                start = editText.getSelectionStart();
                end = editText.getSelectionEnd();
                try {
                    if (sequence.toString().getBytes("GBK").length >15) {
                        s.delete(start - 1, end);
                        int tempSelection = start;
                        editText.setText(s);
                        editText.setSelection(tempSelection);
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 复制内容到剪切板
     * @param copyStr 内容
     */
    public static boolean copy(Context context, String copyStr) {
        try {
            //获取剪贴板管理器
            ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", copyStr);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
